import Watcher from './Watcher';
function Compile(node, vm) {
  if(node) {
    this.$frag = this.nodeToFragment(node, vm);
    return this.$frag;
  }
}
Compile.prototype = {
  nodeToFragment: function(node, vm) {
    const self = this;
    const frag = document.createDocumentFragment();
    let child;
    while(child = node.firstChild) {
      self.compileElement(child, vm);
      frag.append(child); // 将所有子节点添加到fragment中
    }
    return frag;
  },
  compileElement: function(node, vm) {
    const reg = /\{\{(\w*)\}\}/g;

    //节点类型为元素
    if(node.nodeType === 1) {
      if (node.firstChild) {
        this.compileElement(node.firstChild, vm)
      }
      const attr = node.attributes;
      // 解析属性
      for(let i = 0; i < attr.length; i++ ) {
        if(attr[i].nodeName == 'v-model') {
          const name = attr[i].nodeValue; // 获取v-model绑定的属性名
          node.addEventListener('input', function(e) {
            // 给相应的data属性赋值，进而触发该属性的set方法
              vm[name] = e.target.value;
          });
          new Watcher(vm, node, name, 'value');
        }
        if(attr[i].nodeName==='@click' || attr[i].nodeName==='v-on:click'){
          const handle = attr[i].nodeValue;
          node.addEventListener('click', e => {
            vm.methods[handle] && vm.methods[handle].bind(vm)(e)
          })
          node.removeAttribute('@click')
        }
        // if(attr[i].nodeName = 'v-html'){
        //   const html = attr[i].nodeValue;
        //   this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML'))
        //   node.removeAttribute('v-html')
        // }
      }
    }
    //节点类型为text
    if(node.nodeType === 3) {
      if(reg.test(node.nodeValue)) {
        let name = RegExp.$1; // 获取匹配到的字符串
        name = name.trim();
        // node.nodeValue = vm[name]; // 将data的值赋给该node
        new Watcher(vm, node, name, 'nodeValue');
      }
    }
  },
}
export default Compile;